<template src="./data.html">
</template>
<script setup>
import data from '../data.js'
import { getFooterTop, getHeaderBottom, getItemMargin } from '../element'
import {
  onMounted, onUnmounted,
  ref,
  nextTick
} from 'vue'

let start = ref(0)
let end = ref(1)
const itemRefs = ref([])

function init () {
  let index = 0
  ;(function _renderMore () {
    if (index >= data.length) return
    const item = itemRefs.value[index++]
    if (item && item.getBoundingClientRect().bottom < getFooterTop()) {
      end.value++
      nextTick(_renderMore)
    }
  }())
}

function scroll () {
  const firstItem = itemRefs.value[start.value]
  const lastItem = itemRefs.value[end.value - 1]

  if (firstItem.getBoundingClientRect().top > getHeaderBottom()) {
    start.value -= 1
  }
  else if (firstItem.getBoundingClientRect().bottom < getHeaderBottom() - getItemMargin()) {
    start.value += 1
  }
  if (lastItem.getBoundingClientRect().bottom < getFooterTop()) {
    end.value += 1
  }
  else if (lastItem.getBoundingClientRect().top >= getFooterTop() + getItemMargin()) {
    end.value -= 1
  }
  start.value = Math.max(0, start.value)
  end.value = Math.min(data.length, end.value)
}

onMounted(() => init())
onMounted(() => document.addEventListener('scroll', scroll))
onUnmounted(() => document.removeEventListener('scroll', scroll))

function setItemRef (el, item) {
  itemRefs.value[data.indexOf(item)] = el
}
</script>
